package com.diy.sigmund.diycommon.spring.advice;

import com.diy.sigmund.diycommon.entity.ResultMsg;
import com.diy.sigmund.diycommon.entity.base.exception.DiyRuntimeException;
import com.diy.sigmund.diycommon.entity.enumerate.ResponseEnum;
import com.diy.sigmund.diycommon.spring.ContextHolder;
import com.diy.sigmund.diycommon.spring.CustomApplicationContext;
import com.diy.sigmund.diycommon.util.json.JacksonUtil;
import java.util.Objects;
import java.util.concurrent.RejectedExecutionException;
import javax.servlet.DispatcherType;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 自定义的异常能够被正确的捕获并处理
 * 全局异常处理优先处理子类的异常
 * 自义定全局异常处理除了可以处理上述的数据格式之外，也可以处理页面的跳转，只需在新增的异常方法的返回处理上填写该跳转的路径并不使用ResponseBody 注解即可
 * 因为在GlobalExceptionHandler类中使用的是ControllerAdvice注解，而非RestControllerAdvice注解
 *
 * @author ylm-sigmund
 * @since 2021/5/4 11:59
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(RejectedExecutionException.class)
    @ResponseBody
    public ResultMsg rejectedExecutionException(HttpServletRequest req, RejectedExecutionException e) {
        log.error("发生RejectedExecutionException，全局捕获", e);
        if (Objects.equals(DispatcherType.ASYNC.name(),
                CustomApplicationContext.getHttpServletRequest().getDispatcherType().name())) {
            // 之所以这样处理,是因为使用默认的拒绝策略AbortPolicy后,dispatch的还是同一个线程[http-nio-8000-exec-6]
            // 所以出参会返回2个对象,导致格式化(反序列化)问题
            // 因此,处理DispatcherType.ASYNC的出参,设置null
            // 弃用的方案:若自定义拒绝策略(抛自定义异常),会导致业务执行超时,进入超时处理
            log.info("响应报文=null");
            return null;
        }
        final ResultMsg resultMsg = ResultMsg.fail(ResponseEnum.INTERNAL_SERVER_ERROR);
        log.error("异常处理器响应报文={}, {} ms, {},{}", getRequestURI(), getCostTime(), JacksonUtil.toJson(resultMsg), e.getMessage(), e);
        return resultMsg;
    }

    private String getRequestURI() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.isNull(attributes) ? null : attributes.getRequest();
        return Objects.isNull(request) ? "" : request.getRequestURI();
    }

    private long getCostTime() {
        StopWatch stopWatch = ContextHolder.getInstance().getStopWatch();
        stopWatch.stop();
        return stopWatch.getTime();
    }

    /**
     * 处理定义的业务异常
     *
     * @param req HttpServletRequest
     * @param e   DiyRuntimeException
     * @return ResultMsg
     */
    @ExceptionHandler(DiyRuntimeException.class)
    @ResponseBody
    public ResultMsg diyRuntimeException(HttpServletRequest req, DiyRuntimeException e) {
        log.error("发生业务异常，全局捕获", e);
        final ResultMsg resultMsg = ResultMsg.fail(e.getErrorCode(), e.getErrorMsg());
        log.error("异常处理器响应报文={}, {} ms, {},{}", getRequestURI(), getCostTime(), JacksonUtil.toJson(resultMsg), e.getMessage(), e);
        return resultMsg;
    }

    /**
     * 处理空指针异常
     *
     * @param req HttpServletRequest
     * @param e   NullPointerException
     * @return ResultMsg
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public ResultMsg nullPointerException(HttpServletRequest req, NullPointerException e) {
        log.error("发生空指针异常，全局捕获", e);
        final ResultMsg resultMsg = ResultMsg.fail(ResponseEnum.INTERNAL_SERVER_ERROR);
        log.error("异常处理器响应报文={}, {} ms, {},{}", getRequestURI(), getCostTime(), JacksonUtil.toJson(resultMsg), e.getMessage(), e);
        return resultMsg;
    }

    /**
     * 处理其它异常
     *
     * @param req HttpServletRequest
     * @param e   Exception
     * @return ResultMsg
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultMsg exception(HttpServletRequest req, Exception e) {
        log.error("发生未知异常，全局捕获", e);
        final ResultMsg resultMsg = ResultMsg.fail(ResponseEnum.INTERNAL_SERVER_ERROR);
        // final ResultMsg resultMsg = ResultMsg.fail(e.getMessage());
        // 可溯源到Caused by,但是不建议
        // String msg = Objects.isNull(e.getCause()) ? e.getMessage() : e.getCause().getMessage();
        // final ResultMsg resultMsg = ResultMsg.fail(msg);
        log.error("异常处理器响应报文={}, {} ms, {},{}", getRequestURI(), getCostTime(), JacksonUtil.toJson(resultMsg), e.getMessage(), e);
        return resultMsg;
    }
}
